const router = require('koa-router')
const Router = new router()
const MUser = require('../../models/oneUser')
const hashTool = require('../../tool/hash')
const bcrypt = require('bcryptjs') // 加密包
const defaultHead = 'http://upload.jianshu.io/users/upload_avatars/15577806/2815a437-1dac-4e47-88e4-48fb6310af08.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/120/h/120'
const multer = require('koa-multer')

var storage = multer.diskStorage({
    //文件保存路径
    destination: function (req, file, cb) {
        cb(null, 'static/')
    },
    //修改文件名称
    filename: function (req, file, cb) {
        var fileFormat = (file.originalname).split(".");
        cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
    }
})
var upload = multer({ storage: storage })
Router.post("/oneapp/register", async (ctx, next) => {
    ctx.status = 200
    const { username } = ctx.request.body
    const isUsername = await MUser.find({
        username
    })
    if (isUsername.length > 0) {
        ctx.body = {
            msg: "该用户已存在"
        }
    } else {
        const NUser = new MUser({
            username: ctx.request.body.username,
            // password: ctx.request.body.password
            headprotrait: ctx.request.body.headprotrait ? ctx.request.body.headprotrait : defaultHead,
            password: hashTool.getHash(ctx.request.body.password)
        })
        await NUser.save((err, res) => {
            if (err) throw err
            // ctx.body = res
        })
        const { data, headprotrait, username, _id } = NUser
        ctx.body = {
            data,
            headprotrait,
            username,
            _id
        }
    }
})

Router.post("/oneapp/login", async ctx => {
    const { username, password } = ctx.request.body
    const headportrait = ctx.request.body.headportrait ? ctx.request.body.headportrait : defaultHead
    // 先查找该用户
    const check = await MUser.find({
        username
    })
    if (check.length > 0) {
        // 检查密码和加密密码是否一致
        const rolePassword = await bcrypt.compareSync(password, check[0].password);
        if (rolePassword) {
            ctx.body = {
                msg: '登陆成功',
                username,
                headportrait,
                id: check[0]._id
            }
        } else {
            ctx.status = 400
            ctx.body = {
                msg: '密码错误'
            }
        }
    } else {
        ctx.status = 404
        ctx.body = {
            mag: '没有该用户'
        }
    }
})
Router.get("/oneapp/tsetImg", async ctx => {
    ctx.body = {
        img: 'http://localhost:4550/static/meBj.jpg'
    }
})

Router.post("/oneapp/userupper", upload.single('file'), async ctx => {
    ctx.body = {
        filename: ctx.req.file.filename
    }
})

module.exports = Router